package com.cap.bts.crmdp.webservice.mars.client.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.naming.ServiceUnavailableException;

import com.cap.bts.framework.common.exception.AppException;
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;

public class TokenUtil {
	public static AuthenticationResult getAccessTokenFromUserCredentials(AADConfiguration aadConfiguration)
			throws Exception {
		AuthenticationContext context = null;
		AuthenticationResult result = null;
		ExecutorService service = null;
		try {
			service = Executors.newFixedThreadPool(1);
			context = new AuthenticationContext(aadConfiguration.getAuthority(), false, service);
			Future<AuthenticationResult> future = context.acquireToken(aadConfiguration.getResource(),
					aadConfiguration.getClientId(), aadConfiguration.getUserName(), aadConfiguration.getPassword(),
					null);
			result = future.get();
		} finally {
			service.shutdown();
		}
		if (result == null) {
			throw new ServiceUnavailableException("authentication result was null");
		}
		return result;
	}
	
	private void validateAADConfigration(AADConfiguration aadConfiguration) throws AppException{
		if(aadConfiguration.getAuthority()==null){
			throw new AppException("ERROR", "Authority is null!");
		}
		if(aadConfiguration.getResource()==null){
			throw new AppException("ERROR", "Resource is null!");
		}
		if(aadConfiguration.getClientId()==null){
			throw new AppException("ERROR", "ClientId is null!");
		}
		if(aadConfiguration.getUserName()==null){
			throw new AppException("ERROR", "UserName is null!");
		}
		if(aadConfiguration.getPassword()==null){
			throw new AppException("ERROR", "Password is null!");
		}
		
	}
	public static void main(String[] args) throws AppException {
		TokenUtil t = new TokenUtil();
		t.validateAADConfigration(new AADConfiguration());
	}
}
